/**
 * 登陆会话
 */

import storage from '@/utils/storage'

/*
 * mutation 事件类型
 */
const CREATE = 'CREATE'
const FETCH = 'FETCH'
const DELETE = 'DELETE'

// storage key
const STORAGE_KEY = 'admin'

// initial state
const state = {
  user: {}
}

// getters
// store.getters.user -> {"email":"xxxx@xxxx.com","token":"eyJh..."}
const getters = {
  user: state => state.user
}

/**
 * actions 
 * 
 * ES2015 的 参数解构 写法
 * @see https://github.com/lukehoban/es6features#destructuring
 * @see https://vuex.vuejs.org/zh-cn/actions.html
 */
const actions = {
  create({ commit }, user) {
    commit(CREATE, user)
  },

  fetch({ commit }) {
    commit(FETCH)
  },

  delete({ commit }) {
    commit(DELETE)
  }
}

// mutations
const mutations = {

  [FETCH](state) {
    state.user = storage.get(STORAGE_KEY)
  },

  [CREATE](state, user) {
    state.user = user
    storage.set(STORAGE_KEY, user)
  },

  [DELETE](state) {
    storage.remove(STORAGE_KEY)
    state.user = {}
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
